package com.msk.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.msk.base.domain.goods.Goods;
import com.msk.base.service.goods.GoodsService;
import com.msk.common.constant.Constants;
import com.msk.common.constant.UserConstants;
import com.msk.common.core.domain.R;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.common.utils.MessageUtils;
import com.msk.common.utils.StringUtils;
import com.msk.framework.web.utils.TokenUtils;
import com.msk.message.service.ISmsClientService;
import com.msk.sys.domain.User;
import com.msk.sys.service.SysParamService;
import com.msk.sys.service.SystemService;
import com.msk.sys.utils.DictMskUtils;
import com.msk.system.service.impl.SysUserServiceImpl;
import com.msk.wlhy.domain.*;
import com.msk.wlhy.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 系统用户信息
 * @Author zlf
 * @Date 2023/5/17 11:34
 */
@Api(tags = "系统用户管理")
@RequestMapping("/api/userInfo")
@RestController
public class SysUserInfoController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private ISmsClientService smsClientService;

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private HtTransportDetailService htTransportDetailService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private HtLogisticsOrderDetailService htLogisticsOrderDetailService;

    @Autowired
    private HtSupplierService htSupplierService;

    @Autowired
    private HtTransportListService htTransportListService;

    @Autowired
    private TransportCapacitySupplierRelService transportCapacitySupplierRelService;

    @Autowired
    private SysUserServiceImpl userService;

    /**
     * 用户当前用户信息
     * @return
     */
    @ApiOperation("获取用户信息")
    @PostMapping("/getUserInfo")
    public R<?> getUserInfo() {
        R<?> result;
        try {
            JSONObject userInfo = new JSONObject();
            LoginUser mpLoginUser = TokenUtils.getMpLoginUser();
            if (StringUtils.isNotNull(mpLoginUser)) {
                String loginId = mpLoginUser.getLoginId();
                String loginObject = mpLoginUser.getLoginObject();
                User user = systemService.getUser(loginId);
                String userIdentity = user.getUserIdentity();
                if (!loginObject.equals(userIdentity)) {
                    result = R.appFail(2002, "用户身份异常");
                    return result;
                }
                userInfo.put("userIdentity", userIdentity);
                userInfo.put("userInfo", user);
                if ("1".equals(loginObject)) {
                    HtDriverFile driverInfo = TokenUtils.getDriverLogin();
                    if (StringUtils.isNull(driverInfo)) {
                        userInfo.put("isCommitAuth", 0);
                    } else {
                        String name = driverInfo.getName();
                        String isPassCheck = driverInfo.getIsPassCheck();
                        if (StringUtils.isEmpty(name) || "2".equals(isPassCheck)) {
                            userInfo.put("isCommitAuth", 0);
                        } else {
                            userInfo.put("isCommitAuth", 1);
                        }
                    }
                    userInfo.put("driverInfo", driverInfo);
                } else if ("2".equals(loginObject)) {
                    Map<String, Object> goodsMember = TokenUtils.getGoodsMemberLogin();
                    if (StringUtils.isEmpty(goodsMember)) {
                        userInfo.put("isCommitAuth", 0);
                    } else {
                        String name = StringUtils.getString(goodsMember.get("name"));
                        String comName = StringUtils.getString(goodsMember.get("comName"));
                        if (StringUtils.isNotBlank(name) || StringUtils.isNotBlank(comName)) {
                            userInfo.put("isCommitAuth", 1);
                        } else {
                            userInfo.put("isCommitAuth", 0);
                        }
                        if (StringUtils.isBlank(userInfo.getString("name"))) {
                            if (StringUtils.isNotBlank(name)) {
                                user.setName(name);
                            } else {
                                user.setName(comName);
                            }
                        }
                    }

                    userInfo.put("goodsMember", goodsMember);
                } else if ("3".equals(loginObject)) {
                    HtSupplier supplier = TokenUtils.getSupplierLogin();
                    if (StringUtils.isNull(supplier)) {
                        userInfo.put("isCommitAuth", 0);
                    } else {
                        String name = supplier.getName();
                        if (StringUtils.isEmpty(name)) {
                            userInfo.put("isCommitAuth", 0);
                        } else {
                            userInfo.put("isCommitAuth", 1);
                        }
                    }
                    userInfo.put("supplier", supplier);
                }
            }
            result = R.appOk(userInfo, "登录成功");
        } catch (Exception e) {
            result = R.appFail(2000, "获取信息失败");
        }
        return result;
    }

    /**
     * 修改密码
     * @param
     * @return
     */
    @PostMapping("/modifyPassword")
    @ApiOperation("修改密码")
    @ResponseBody
    public R<?> modifyPassword(@RequestBody User user) {
        R<?> result;
        try {
            String mobile = user.getMobile();
            String password = user.getPassword();
            String validateCode = user.getValidateCode();
            String userIdentity = user.getUserIdentity();
            if (StringUtils.isAnyEmpty(mobile, password, validateCode, userIdentity)) {
                return R.appFail(2001, "参数缺失");
            }
            if (mobile.length() != UserConstants.PHONE_MIN_LENGTH) {
                return R.appFail(2001, "手机号范围错误");
            }
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH_NEW) {
                return R.appFail(2001, "密码长度不符合规范");
            }
            if (!"1".equals(userIdentity) && !"2".equals(userIdentity) && !"3".equals(userIdentity)) {
                return R.appFail(2001, "身份类型错误");
            }
            LoginUser mpLoginUser = TokenUtils.getMpLoginUser();
            if (StringUtils.isNull(mpLoginUser)) {
                return R.appFail(Constants.APP_TOKEN_FAIL, "登录认证已过期");
            }
            String phone = mpLoginUser.getPhone();
            if (!mobile.equals(phone)) {
                return R.appFail(2001, "手机号匹配错误");
            }
            User userInfo = systemService.getByMobile(mobile, userIdentity);
            if (StringUtils.isNull(userInfo)) {
                return R.appFail(2002, "该手机号不存在");
            }
            //验证码开关0:开，1关
            String validateCodeSwitch = DictMskUtils.getDictLabel("1", "validate_code_switch", "0");
            if ("1".equals(validateCodeSwitch)) {
                if (!"9999".equals(validateCode)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            } else {
                String phoneCodeCache = smsClientService.getPhoneCodeCache(mobile);
                if (!validateCode.equals(phoneCodeCache)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            }
            int rows = systemService.updatePasswordById(userInfo.getId(), password);
            if (rows > 0) {
                result = R.appOk("修改成功");
            } else {
                result = R.appFail(2002, "修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = R.appFail(2000, "修改失败");
        }
        return result;
    }

    /**
     * 描述:关于我们
     * @author yangjy
     * @date 2023/7/13 17:07
     * @param
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation("关于我们")
    @PostMapping("/aboutUs")
    public R<?> aboutUs() {
        List<Map<String, Object>> sysParams = sysParamService.aboutUsAndRegistration();
        String about = null;
        for (Map<String, Object> par : sysParams) {
            String aboutUs = String.valueOf(par.get("aboutUs"));
            try {
                about = URLDecoder.decode(aboutUs, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            par.put("aboutUs", about);
        }
        return R.appOk(sysParams);
    }

    /**
     * @date 2023/8/7 9:43
     * @param params
     * @description 用户注销校验
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation("用户注销校验")
    @PostMapping("/logoutCheck")
    public R<?> logoutCheck(@RequestBody Map<String,String> params){
        String userIdentity = params.get("userIdentity");
        if(StringUtils.isBlank(userIdentity)){
            return R.appFail(400101, "请求参数用户身份#为空");
        }
        Map<String,Object> result = new HashMap<>();
        boolean flag = false;
        result.put("flag",flag);

        //司机
        if("1".equals(userIdentity)){
            HtDriverFile driverFile = TokenUtils.getDriverLogin();
            //未认证
            if(driverFile == null){
                flag = true;
                result.put("flag",flag);
                return R.appOk(result);
            }
            if(!"0".equals(driverFile.getDriverStatus())){
                result.put("message","当前司机非闲置状态");
                return R.appOk(result);
            }
            //查询运单数量
            HtTransportDetail htTransportDetail = new HtTransportDetail();
            htTransportDetail.setDriverId(driverFile.getId());
            HtTransportDetail complateDetailCount = htTransportDetailService.findComplateDetailCount(htTransportDetail, "", "", "");
            String received = complateDetailCount.getAttstr04(); //已签收
            String total = complateDetailCount.getAttstr05(); //总运单数
            if(!received.equals(total)){
                result.put("message","当前司机运单未全部完成");
                return R.appOk(result);
            }
            //查询竞价中询价货源
            List<Map<String, Object>> inquiryList = goodsService.selectSourceInquiryListByContact(driverFile.getId(), "1");
            if(!inquiryList.isEmpty()){
                result.put("message","当前司机存在竞价中货源");
                return R.appOk(result);
            }
            //判断司机是否关联承运商
            TransportCapacitySupplierRel transportCapacitySupplierRel = new TransportCapacitySupplierRel();
            transportCapacitySupplierRel.setDriverId(driverFile.getId());
            List<Map<String, Object>> supplierRelList = transportCapacitySupplierRelService.findSupplierRelList(transportCapacitySupplierRel);
            if(!supplierRelList.isEmpty()){
                result.put("message","您关联的承运商未解绑");
                return R.appOk(result);
            }
            flag = true;
            result.put("flag",flag);
        }

        //货主
        if("2".equals(userIdentity)){
            Map<String, Object> goodsMember = TokenUtils.getGoodsMemberLogin();
            //未认证
            if(goodsMember == null){
                flag = true;
                result.put("flag",flag);
                return R.appOk(result);
            }
            LoginUser loginUser = TokenUtils.getMpLoginUser();
            //查询在途运单
            HtTransportDetail htTransportDetail = new HtTransportDetail();
            if(loginUser != null){
                htTransportDetail.setDriverId(loginUser.getLoginId());
                htTransportDetail.setStatus("2"); //已发运
            }
            List<Map<String, Object>> goodsWayBillList = htTransportDetailService.findGoodsWayBillList(htTransportDetail);
            if (!goodsWayBillList.isEmpty()){
                result.put("message","当前货主运单未完成");
                return R.appOk(result);
            }
            //查询未托运的托运单列表
            HtLogisticsOrderDetail htLogisticsOrderDetail = new HtLogisticsOrderDetail();
            if(goodsMember != null){
                String companyId = String.valueOf(goodsMember.get("company1Id"));
                htLogisticsOrderDetail.setConsigner(companyId);
                htLogisticsOrderDetail.setGenerateStatus("0");
            }
            List<Map<String,Object>> consignmentList = htLogisticsOrderDetailService.selectConsignerLogisticsOrderDetailList(htLogisticsOrderDetail);
            if(!consignmentList.isEmpty()){
                result.put("message","当前货主存在未托运的运单");
                return R.appOk(result);
            }
            //查询未签约的货源
            Goods goods = new Goods();
            goods.setUserIdentity("2");
            goods.setCreateId(loginUser.getLoginId());
            goods.setPublishWay("3"); //竞价发布
            goods.setType("10"); //未签约
            Integer count = goodsService.getUnsignedCount(goods);
            if(count != 0){
                result.put("message","当前货主存在未签约的货源");
                return R.appOk(result);
            }
            flag = true;
            result.put("flag",flag);
        }

        //承运商
        if("3".equals(userIdentity)){
            HtSupplier supplierLogin = TokenUtils.getSupplierLogin();
            //未认证
            if(supplierLogin == null){
                flag = true;
                result.put("flag",flag);
                return R.appOk(result);
            }
            HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(TokenUtils.getMpLoginUser().getLoginId());
            String id = htSupplier.getId();
            List<Map<String, Object>> maps = htTransportListService.htTransportCount(new HtTransportList(id));
            HtLogisticsOrderDetail htLogisticsOrderDetail = new HtLogisticsOrderDetail();
            htLogisticsOrderDetail.setSupplier(htSupplier);
            List<Map<String, Object>> list = htLogisticsOrderDetailService.selectShippingOrderList(htLogisticsOrderDetail);
            String biddingStatus = null;
            List<Map<String, Object>> goodsList = goodsService.selectSourceInquiryListByContact(id, biddingStatus);
            for(Map<String, Object> ls : list){
                String goodsWeight = String.valueOf(ls.get("goodsWeight"));
                String realGoodsWeight = String.valueOf(ls.get("realGoodsWeight"));
                if(!goodsWeight.equals(realGoodsWeight)){
                    result.put("message","您有未完成的运单或未结算的运单");
                    return R.appOk(result);
                }
            }
            for(Map<String, Object> map : maps){
                String moneyReceipt = String.valueOf(map.get("moneyReceipt"));
                String totalNumber = String.valueOf(map.get("totalNumber"));
                if(!moneyReceipt.equals(totalNumber)){
                    result.put("message","您有未完成的运单或未结算的运单");
                    return R.appOk(result);
                }
            }
            for(Map<String, Object>goods : goodsList){
                String biddingSta = String.valueOf(goods.get("biddingStatus"));
                if("1".equals(biddingSta)){
                    result.put("message","您有正在竞价中的货源");
                    return R.appOk(result);
                }
            }
            flag = true;
            result.put("flag",flag);
        }
        return R.appOk(result);
    }

    /**
     * @date 2023/8/7 14:36
     * @description 用户注销
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation("用户注销")
    @PostMapping("/logout")
    public R<?> logout(){
        LoginUser mpLoginUser = TokenUtils.getMpLoginUser();
        String loginId = mpLoginUser.getLoginId();
        if(StringUtils.isNotEmpty(loginId)){
            userService.deletelogoutUser(loginId);
        }
        return R.appOk("注销成功");
    }
}
